package com.wakala.employment.activity;

import static androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.config.IToastStyle;
import com.hjq.toast.style.CustomToastStyle;
import com.kongzue.dialogx.DialogX;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.FullScreenDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.DialogXStyle;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.style.MaterialStyle;
import com.leaf.library.StatusBarUtil;
import com.umeng.message.PushAgent;
import com.wakala.employment.MyApp;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.XFragmentAdapter;
import com.wakala.employment.adapter.bean.UserAddress;
import com.wakala.employment.core.BaseActivity;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.bean.EventKey;
import com.wakala.employment.core.constants.UserRoleEnum;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.ActivityMainBinding;
import com.wakala.employment.fragment.circle.CircleRecommendFragment;
import com.wakala.employment.fragment.finder.JobFinderFragment;
import com.wakala.employment.fragment.member.MemberFragment;
import com.wakala.employment.fragment.message.MessageFragment;
import com.wakala.employment.fragment.news.NewsFragment;
import com.wakala.employment.fragment.other.AboutFragment;
import com.wakala.employment.fragment.other.BlankFragment;
import com.wakala.employment.fragment.other.SettingsFragment;
import com.wakala.employment.fragment.profile.ProfileFragment;
import com.wakala.employment.fragment.profile.ResumeFragment;
import com.wakala.employment.fragment.recruit.RecruitFragment;
import com.wakala.employment.fragment.recruit.RecruitIssueFragment;
import com.wakala.employment.fragment.subscribe.SubscribeJobFragment;
import com.wakala.employment.fragment.trending.RecruitmentFragment;
import com.wakala.employment.fragment.trending.TrendingFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.DeviceTokenBo;
import com.wakala.employment.utils.MMKVUtils;
import com.wakala.employment.utils.sdkinit.XUpdateInit;
import com.wakala.employment.widget.GuideTipsDialog;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.rxutil2.rxbus.RxEvent;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.adapter.FragmentAdapter;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.ClickUtils;
import com.xuexiang.xutil.common.CollectionUtils;
import com.xuexiang.xutil.system.DeviceUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.lang.reflect.Field;
import java.util.Arrays;

import io.reactivex.functions.Consumer;

/**
 * 程序主页面,只是一个简单的Tab例子
 *
 * @author weixiaoliang
 * @since 2019-07-07 23:53
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> implements View.OnClickListener, BottomNavigationView.OnNavigationItemSelectedListener, ClickUtils.OnClick2ExitListener, Toolbar.OnMenuItemClickListener {

    private static final String TAG = "MainActivity";
    private String[] mTitles;

    private BaseFragment[] fragments;

    private FragmentAdapter<BaseFragment> adapter;

    private boolean isToIssue;

    @Override
    protected ActivityMainBinding viewBindingInflate(LayoutInflater inflater) {
        return ActivityMainBinding.inflate(inflater);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initViews();

        initData();

        initListeners();
    }


    @Override
    protected boolean isSupportSlideBack() {
        return false;
    }

    private void initViews() {
        WidgetUtils.clearActivityBackground(this);
        mTitles = ResUtils.getStringArray(R.array.home_titles);
        binding.includeMain.toolbar.setTitle(mTitles[0]);
        binding.includeMain.toolbar.inflateMenu(R.menu.menu_main);
        binding.includeMain.toolbar.setOnMenuItemClickListener(this);

        initHeader();

        //StatusBarUtil.setTransparentForWindow(this);
        StatusBarUtil.setDarkMode(this);
        getWindow().setStatusBarColor(getResources().getColor(R.color.white));

        //主页内容填充
        fragments = new BaseFragment[]{
                new JobFinderFragment(),//找活
                new RecruitFragment(),//招工
                new TrendingFragment(),//圈子
                new MessageFragment(),//消息
                new MemberFragment(),//会员
                new RecruitmentFragment()//订阅
        };
        //设置fragment懒加载，设置 BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        adapter = new FragmentAdapter<>(getSupportFragmentManager(),BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, fragments);
        //设置viewpage预加载fragment的数量 默认是1
        binding.includeMain.viewPager.setOffscreenPageLimit(mTitles.length - 1);
        binding.includeMain.viewPager.setAdapter(adapter);
        binding.includeMain.viewPager.setNoScroll(true);
        //
        initBottomNavigationView();
    }

    private void initData() {
        GuideTipsDialog.showTips(this);
        XUpdateInit.checkUpdate(this, false);
        //检查并获umeng设备id
        String deviceToken = PushAgent.getInstance(this).getRegistrationId();
        Log.i(TAG, "获取友盟推送成功 device token: " + deviceToken);
        DeviceTokenBo deviceTokenBo = new DeviceTokenBo();
        deviceTokenBo.setAndroidId(DeviceUtils.getAndroidID());
        deviceTokenBo.setAndroidVersionName(DeviceUtils.getAndroidVersionName());
        deviceTokenBo.setDeviceModel(DeviceUtils.getDeviceModel());
        deviceTokenBo.setManufacturer(DeviceUtils.getManufacturer());
        deviceTokenBo.setSdkVersionCode(DeviceUtils.getSDKVersionCode()+"");
        deviceTokenBo.setSdkVersionName(DeviceUtils.getSDKVersionName());
        deviceTokenBo.setUmengDeviceToken( deviceToken);
        updateDeviceToken(deviceTokenBo);
    }

    private void initHeader() {

    }

    private void initBottomNavigationView(){
        //去除底部菜单点击时的默认阴水波纹影效果
        binding.includeMain.bottomNavigation.setItemBackground(getResources().getDrawable(R.drawable.botoom_menu_selector));
    }

    protected void initListeners() {

        binding.fabBtnPub.setOnClickListener(this);
        binding.fabBtnLeft.setOnClickListener(this);
        binding.fabBtnRight.setOnClickListener(this);

        //主页事件监听
        binding.includeMain.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(position==5){
                    position=2;
                }
                MenuItem item = binding.includeMain.bottomNavigation.getMenu().getItem(position);
                binding.includeMain.toolbar.setTitle(item.getTitle());
                item.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.includeMain.bottomNavigation.setOnNavigationItemSelectedListener(this);
        //
        RxBusUtils.get().on(EventKey.EVENT_BUTTON_RECRUIT_CLICK, RxEvent.class, new Consumer<RxEvent>() {
            @Override
            public void accept(RxEvent event) throws Exception {
                //RxToast.success("事件key:"+EventKey.EVENT_HAVE_DATA);
                MenuItem item = binding.includeMain.bottomNavigation.getMenu().getItem(1);
                binding.includeMain.bottomNavigation.setSelectedItemId(item.getItemId());
                isToIssue = true;
            }
        });
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_privacy) {
            GuideTipsDialog.showTipsForce(this);
        } else if (id == R.id.action_about) {
            openNewPage(AboutFragment.class);
        }
        return false;
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.nav_header) {
            XToastUtils.toast("点击头部！");
        } else if (id==R.id.fab_btn_left) {
            //XToastUtils.toast("免费发布招工！");
            MenuItem item = binding.includeMain.bottomNavigation.getMenu().getItem(1);
            binding.includeMain.bottomNavigation.setSelectedItemId(item.getItemId());
            isToIssue = true;
        } else if (id==R.id.fab_btn_right) {
            //XToastUtils.toast("管理找活简历！");
            openNewPage(ResumeFragment.class);
        } else if (id==R.id.fab_btn_pub) {
            //XToastUtils.toast("免费发布招工！！");
            openNewPage(RecruitIssueFragment.class);
        }
    }

    //================Navigation================//

    /**
     * 底部导航栏点击事件
     *
     * @param menuItem
     * @return
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int index = CollectionUtils.arrayIndexOf(mTitles, menuItem.getTitle());
        if (index != -1) {
            if (menuItem.getItemId()==R.id.nav_news) {//找活

                // 切换提示
                if(MyApp.User_Role!=UserRoleEnum.CANDIDATE) {
                    FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.dialog_role_switch) {
                        @Override
                        public void onBind(FullScreenDialog dialog, View v) {
                            TextView title = v.findViewById(R.id.tv_title);
                            title.setText("您当前的身份是“老板”");
                            ImageView headImg = v.findViewById(R.id.member_img);
                            headImg.setImageResource(R.mipmap.style_boss);
                            Button btnRoleSwitch = v.findViewById(R.id.btn_role_switch);
                            btnRoleSwitch.setOnClickListener(view -> {
                                binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                                binding.includeMain.viewPager.setCurrentItem(index, false);
                                dialog.dismiss();
                                toasterShow("您已经成功切换到找活端");
                                //
                                binding.fabViewRelative.setVisibility(View.VISIBLE);
                                binding.fabBtnLeft.setVisibility(View.VISIBLE);
                                binding.fabBtnRight.setVisibility(View.VISIBLE);
                                binding.fabBtnPub.setVisibility(View.GONE);
                                //
                                MyApp.User_Role = UserRoleEnum.CANDIDATE;
                                //
                                // 获取底部导航栏的菜单
                                Menu menu = binding.includeMain.bottomNavigation.getMenu();
                                // 修改菜单项的图标
                                MenuItem menuItem = menu.findItem(R.id.nav_book_job);
                                menuItem.setIcon(R.drawable.ic_book_job);
                                menuItem.setTitle(getString(R.string.menu_book_job));
                                /// 刷新底部导航栏
                                binding.includeMain.bottomNavigation.invalidate();
                            });
                            Button btnCancel = v.findViewById(R.id.btn_cancel);
                            btnCancel.setOnClickListener(view -> {
                                dialog.dismiss();
                            });
                            btnRoleSwitch.setText("切换到“牛人”身份");

                        }
                    }).setCancelable(false);
                }else {
                    binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                    binding.includeMain.viewPager.setCurrentItem(index, false);
                    //
                    binding.fabViewRelative.setVisibility(View.VISIBLE);
                    binding.fabBtnLeft.setVisibility(View.VISIBLE);
                    binding.fabBtnRight.setVisibility(View.VISIBLE);
                    binding.fabBtnPub.setVisibility(View.GONE);
                }
            } else if (menuItem.getItemId()==R.id.nav_trending) {//招工

                // 切换提示
                if(MyApp.User_Role!=UserRoleEnum.BOOS) {

                    FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.dialog_role_switch) {
                        @Override
                        public void onBind(FullScreenDialog dialog, View v) {
                            TextView title = v.findViewById(R.id.tv_title);
                            title.setText("您当前的身份是“牛人”");
                            ImageView headImg = v.findViewById(R.id.member_img);
                            headImg.setImageResource(R.mipmap.style_worker);
                            Button btnRoleSwitch = v.findViewById(R.id.btn_role_switch);
                            btnRoleSwitch.setOnClickListener(view -> {
                                binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                                binding.includeMain.viewPager.setCurrentItem(index, false);
                                dialog.dismiss();
                                toasterShow("您已经成功切换到老板端");
                                //
                                binding.fabViewRelative.setVisibility(View.VISIBLE);
                                binding.fabBtnLeft.setVisibility(View.GONE);
                                binding.fabBtnRight.setVisibility(View.GONE);
                                binding.fabBtnPub.setVisibility(View.VISIBLE);
                                //
                                MyApp.User_Role = UserRoleEnum.BOOS;
                                if(isToIssue){
                                    isToIssue = false;
                                    openNewPage(RecruitIssueFragment.class);
                                }
                                //
                                // 获取底部导航栏的菜单
                                Menu menu = binding.includeMain.bottomNavigation.getMenu();
                                // 修改菜单项的图标
                                MenuItem menuItem = menu.findItem(R.id.nav_book_job);
                                menuItem.setIcon(R.drawable.ic_admin_employ);
                                menuItem.setTitle(getString(R.string.menu_admin_employ));
                                /// 刷新底部导航栏
                                binding.includeMain.bottomNavigation.invalidate();
                            });
                            Button btnCancel = v.findViewById(R.id.btn_cancel);
                            btnCancel.setOnClickListener(view -> {
                                dialog.dismiss();
                            });
                            btnRoleSwitch.setText("切换到“老板”身份");
                        }
                    }).setCancelable(false);
                }else {
                    binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                    binding.includeMain.viewPager.setCurrentItem(index, false);
                    //
                    binding.fabViewRelative.setVisibility(View.VISIBLE);
                    binding.fabBtnLeft.setVisibility(View.GONE);
                    binding.fabBtnRight.setVisibility(View.GONE);
                    binding.fabBtnPub.setVisibility(View.VISIBLE);
                }
            } else if (menuItem.getItemId()==R.id.nav_book_job) {//订阅工作 | 管理招工
                binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                binding.includeMain.viewPager.setCurrentItem(index, false);
                binding.fabViewRelative.setVisibility(View.GONE);
            } else if(menuItem.getItemId()==R.id.nav_message) {//消息
                binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                binding.includeMain.viewPager.setCurrentItem(index, false);
                binding.fabViewRelative.setVisibility(View.GONE);
            } else if (menuItem.getItemId()==R.id.nav_profile) {//会员
                binding.includeMain.toolbar.setTitle(menuItem.getTitle());
                binding.includeMain.viewPager.setCurrentItem(index, false);
                binding.fabViewRelative.setVisibility(View.GONE);
                Log.i("",menuItem.getTitle().toString());
                binding.includeMain.toolbar.setTitle("会员中心");
            }
            return false;
        }
        return true;
    }

    private void  toasterShow(String text){
       /* ToastParams params = new ToastParams();
        params.text = text;
        params.style = new CustomToastStyle(R.layout.toaster_text_larger);
        Toaster.show(params);*/
        PopTip.show(text);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBusUtils.get().unregisterAll(EventKey.EVENT_BUTTON_RECRUIT_CLICK);
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ClickUtils.exitBy2Click(2000, this);
        }
        return true;
    }

    @Override
    public void onRetry() {
        XToastUtils.toast("再按一次退出程序");
    }

    @Override
    public void onExit() {
        XUtil.exitApp();
    }

    @SuppressLint("CheckResult")
    private void updateDeviceToken(DeviceTokenBo deviceTokenBo){
     /*   DeviceTokenBo deviceTokenBo = new DeviceTokenBo();
        deviceTokenBo.setAndroidId(DeviceUtils.getAndroidID());
        deviceTokenBo.setAndroidVersionName(DeviceUtils.getAndroidVersionName());
        deviceTokenBo.setDeviceModel(DeviceUtils.getDeviceModel());
        deviceTokenBo.setManufacturer(DeviceUtils.getManufacturer());
        deviceTokenBo.setSdkVersionCode(DeviceUtils.getSDKVersionCode()+"");
        deviceTokenBo.setSdkVersionName(DeviceUtils.getSDKVersionName());
        deviceTokenBo.setUmengDeviceToken( MMKVUtils.getString(MMKVUtils.KEY_UMENG_DEVICE_TOKEN,""));*/
        XHttpProxy.proxy(TestApi.IUserService.class)
                .updateDeviceToken(deviceTokenBo)
                .subscribeWith(new NoTipRequestSubscriber<Object>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(Object object) {
                        Log.i(TAG, "updateDeviceToken onSuccess");
                    }
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        Log.i(TAG, "updateDeviceToken oError");
                    }
                });
    }


}
